﻿using System;
using System.IO;
using System.Web;
using System.Web.UI.WebControls;
using ASPNETVN.PORTAL.Components.Share;
using ASPNETVN.PORTAL.Components.UI;
using ASPNETVN.PORTAL.Modules.ACTP.Components;
using ASPNETVN.PORTAL.Components.Helpers;

namespace ASPNETVN.PORTAL.Modules.ACTP.Controls
{
    public partial class DocumentList : ModulePage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            btnAdd.Visible = this.IsAddable;
            //gvList.Columns[gvList.Columns.Count - 1].Visible = this.IsEditable;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                Project project = Project.Load(this.ItemID);
                if (project != null)
                {
                    lblSubject.Text = project.Subject;
                }
                
                //gvList.DataSource = ASPNETVN.PORTAL.Components.Share.Attachment.SelectCollectionBy_ModuleID_ItemID(this.ModuleID, this.ItemID);
                //gvList.DataBind();
            }
        }

        protected void btnRefresh_Click(object sender, EventArgs e)
        {
            //gvList.DataSource = ASPNETVN.PORTAL.Components.Share.Attachment.SelectCollectionBy_ModuleID_ItemID(this.ModuleID, this.ItemID);
            //gvList.DataBind();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            // Go to upload file page.
            string returnUrl = HttpUtility.UrlEncode(HttpUrlBuilder.BuildModulePageUrl(this.ModuleID, this.ItemID, ModulePages.DocumentList));
            string url = HttpUrlBuilder.BuildShareUrl(this.ModuleID, this.ItemID, "UploadFile", "returnurl={0}", returnUrl);
            Response.Redirect(url);
        }

        protected void DataListAttachment_DeleteCommand(object source, DataListCommandEventArgs e)
        {
            int ret = Attachment.DeleteAttachment(Convert.ToInt32(DataListAttachment.DataKeys[e.Item.ItemIndex]));
            if (ret > 0)
            {
                if (this.Settings["StorageType"].ToString().ToUpper().Equals("FILE"))
                {
                    string filename = this.Server.MapPath("~/Uploads/" + this.ModuleID + "/" + e.CommandArgument);
                    if (File.Exists(filename))
                    {
                        File.Delete(filename);
                    }
                }
                DataListAttachment.DataBind();
            }
        }

    }
}